package com.mall.controller;

import com.mall.entity.CodeNumEntity;
import com.mall.entity.ResponseMessage;
import com.mall.util.StringUtil;
import com.mall.util.UploadFileUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: liang
 * @time: 2023-12-27 19:25
 */
@RestController
public class FileUploadController {


    private String uploadDir;

    @PostMapping("/upload")
    public ResponseMessage uploadFile(@RequestParam("file") List<MultipartFile> files) {

        List<String> urls = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        try {
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                String contentType = file.getContentType();
                long fileSize = file.getSize();

                // Get file input stream


                // Process the file as needed
                // ...

                // In this example, we just print file information to the console
                System.out.println("File Name: " + fileName);
                System.out.println("Content Type: " + contentType);
                System.out.println("File Size: " + fileSize + " bytes");

                String suffix = fileName.substring(fileName.lastIndexOf("."));
                fileName = StringUtil.getUUIDRandomString(10) + suffix;

                String url = UploadFileUtil.uplaodFile(file.getInputStream(), fileName);
                urls.add(url);

                // You can use 'fileContent' InputStream to read the file content
                // ...

                // Do further processing based on your requirements
                // ...
            }

            map.put("message", urls);
            return new ResponseMessage(CodeNumEntity.SUCCESS.getCode(), CodeNumEntity.SUCCESS.getMessage(), map);

        } catch ( IOException e) {
            e.printStackTrace();
            return new ResponseMessage(CodeNumEntity.SERVER_ERROR.getCode(), CodeNumEntity.SERVER_ERROR.getMessage());

        }
    }
}
